<template>
  <div>
    <div class="title">
      <p class="con-title">
        <span>
          <img src="@/assets/img/control/content/Group769.png" />
        </span>
        <span>合同内容</span>
      </p>
    </div>
    <el-table border :data="contractForm.orderItems" header-cell-class-name="title-style">
      <el-table-column prop="sn" label="订单号" align="center" />
      <el-table-column label="订单类型" align="center">
        <template #default="scope">
          {{ getEnumsLabel(scope.row.shoppingCarEnums) }}
        </template>
      </el-table-column>
      <el-table-column prop="updatePrice" label="实付金额(元)" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column v-if="!contractId" label="操作" align="center">
        <template #default="scope">
          <el-button @click="handleDelete(scope.row, scope.$index)" type="danger">
            删除
          </el-button>
        </template>
      </el-table-column>
      <template v-slot:empty>
        <div class="empty">
          <el-text type="info">尚未选择任何已支付订单</el-text>
          <el-button link type="primary" @click="handleOrder">选择订单</el-button>
        </div>
      </template>
    </el-table>

    <div class="title">
      <p class="con-title">
        <span>
          <img src="@/assets/img/control/content/Group769.png" />
        </span>
        <span>合同双方信息</span>
      </p>
    </div>
    <el-form
      label-position="left"
      label-width="170px"
      ref="contractRef"
      :model="contractForm"
      :rules="contractId ? {} : contractRules"
      style="max-width: 800px"
    >
      <el-form-item label="地址" prop="userAddress">
        <span v-if="contractId">{{ contractForm.userAddress || "无" }}</span>
        <el-input v-else v-model="contractForm.userAddress" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="联系人姓名" prop="userName">
        <span v-if="contractId">{{ contractForm.userName || "无" }}</span>
        <el-input v-else v-model="contractForm.userName" placeholder="请输入联系人姓名" />
      </el-form-item>
      <el-form-item label="联系人电话" prop="userContactPhone">
        <span v-if="contractId">{{ contractForm.userContactPhone || "无" }}</span>
        <el-input
          v-else
          v-model="contractForm.userContactPhone"
          maxlength="11"
          placeholder="请输入联系人电话"
        />
      </el-form-item>
      <el-form-item label="开户银行" prop="userBankOfDeposit">
        <span v-if="contractId">{{ contractForm.userBankOfDeposit || "无" }}</span>
        <el-input
          v-else
          v-model="contractForm.userBankOfDeposit"
          placeholder="请输入开户银行"
        />
      </el-form-item>
      <el-form-item label="银行账号" prop="userAccountNumber">
        <span v-if="contractId">{{ contractForm.userAccountNumber || "无" }}</span>
        <el-input
          v-else
          v-model="contractForm.userAccountNumber"
          placeholder="请输入银行账号"
        />
      </el-form-item>
      <el-form-item label="纳税人识别号" prop="userTaxpayerNumber">
        <span v-if="contractId">{{ contractForm.userTaxpayerNumber || "无" }}</span>
        <el-input
          v-else
          v-model="contractForm.userTaxpayerNumber"
          placeholder="请输入纳税人识别号"
        />
      </el-form-item>
      <div class="title" style="margin: 30px 0">
        <p class="con-title">
          <span>
            <img src="@/assets/img/control/content/Group769.png" />
          </span>
          <span>四川智慧华云大数据有限公司信息</span>
        </p>
      </div>
      <el-form-item label="地址" prop="companyAddress">
        {{ contractForm.companyAddress || "无" }}
      </el-form-item>
      <el-form-item label="联系人姓名" prop="companyName">
        {{ contractForm.companyName || "无" }}
      </el-form-item>
      <el-form-item label="联系人电话" prop="companyContactPhone">
        {{ contractForm.companyContactPhone || "无" }}
      </el-form-item>
      <el-form-item label="收款账号" prop="companyAccountNumber">
        {{ contractForm.companyAccountNumber || "无" }}
      </el-form-item>
    </el-form>
    <div style="marginleft: 200px">
      <!-- <el-button type="primary"> 保存合同草稿 </el-button> -->
      <el-button
        type="primary"
        v-if="!contractId"
        plain
        @click="handleCreate(contractRef)"
      >
        创建正式合同
      </el-button>
    </div>
    <el-dialog v-model="orderShow" width="60%">
      <template #header>
        <div class="title">
          <p class="con-title">
            <span>
              <img src="@/assets/img/control/content/Group769.png" />
            </span>
            <span>选择已支付订单</span>
          </p>
        </div>
      </template>
      <div class="query">
        <span>
          已选择{{ contractForm.orderItems.length || 0 }}项，实际总金额 ¥{{ amount || 0 }}
        </span>
        <el-date-picker
          v-model="queryParams.params.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择起始时间"
          @change="getOrderList"
          style="width: 200px; margin-left: 10px"
        />
        <el-date-picker
          v-model="queryParams.params.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
          @change="getOrderList"
          style="width: 200px; margin-left: 10px"
        />
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入订单编号"
          clearable
          @change="getOrderList"
          style="width: 200px; margin-left: 10px"
        />
      </div>
      <div class="tips">
        <span style="color: #909090"
          >一个订单只能申请一个合同，若需要申请多个合同申请点击
          <span style="color: #ff6e40">申请线上合同</span></span
        >
      </div>
      <el-table border :data="orderList" header-cell-class-name="title-style">
        <el-table-column prop="sn" label="订单号" align="center" />
        <el-table-column label="订单类型" align="center">
          <template #default="scope">
            {{ getEnumsLabel(scope.row.shoppingCarEnums) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatePrice" label="实付金额(元)" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="handleAdd(scope.row)" type="primary">选择</el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <div class="empty">
            <el-text type="info">尚未选择任何已支付订单</el-text>
            <el-button link type="primary" @click="handleOrder">选择订单</el-button>
          </div>
        </template>
      </el-table>
      <div class="page-footer">
        <el-pagination
          :total="orderTotal"
          v-model:current-page="queryParams.params.pageNum"
          v-model:page-size="queryParams.params.pageSize"
          layout="total, prev, pager, next"
          small
          @size-change="getOrderList"
          @current-change="getOrderList"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from 'element-plus'

import {
  contractInfo,
  contractCompany,
  contractAdd,
  itemList,
} from "@/api/control/order";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

const contractId = ref<any>(""); // 合同ID
const contractRef = ref<FormInstance>();
const contractForm = ref<any>({
  id: "",
  userAddress: "", // 用户地址
  userContactPhone: "", // 用户电话
  userName: "", // 用户姓名
  userBankOfDeposit: "", // 用户开户银行
  userAccountNumber: "", // 用户银行账号
  userTaxpayerNumber: "", // 用户纳税人识别号

  companyAddress: "", // 地址
  companyContactPhone: "", // 联系人电话
  companyName: "", // 联系人姓名
  companyAccountNumber: "", // 收款账号
  orderItems: [], // 订单列表(回显)
  orderItemIds: [], // 订单IDs
});
const contractRules = ref<any>({
  // 验证规则
  userAddress: [{ required: true, message: "请输入用户地址", trigger: "blur" }],
  userContactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
    {
      pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
      message: "请输入正确的联系人电话",
      trigger: "blur",
    },
  ],
  userName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  userBankOfDeposit: [{ required: true, message: "请输入开户银行", trigger: "blur" }],
  userAccountNumber: [{ required: true, message: "请输入银行账号", trigger: "blur" }],
  userTaxpayerNumber: [
    { required: true, message: "请输入纳税人识别号", trigger: "blur" },
  ],
});

const queryParams = ref<any>({
  sn: null,
  contractStatus: 2,
  orderStatus: "SUCCESS",
  params: {
    startTime: "",
    endTime: "",
    pageNum: 1,
    pageSize: 10,
  },
});
const orderList = ref<any>([]); // 订单列表
const orderTotal = ref(0); // 总条数
const amount = ref(0); // 已选订单金额
const orderShow = ref(false);

const typeList = ref<any>([
  { value: "CLOUD_SERVER", label: "云服务器" },
  { value: "CLOUD_MARKET", label: "云市场" },
  { value: "GOV_CLOUD", label: "政务云" },
]);

onMounted(() => {
  let id = route.query.id;
  if (id) {
    contractId.value = id;
    getInfo();
  } else {
    getCompany();
  }
});

// 查询合同详情
const getInfo = () => {
  contractInfo(contractId.value).then((res: any) => {
    contractForm.value = res.data;
  });
};

// 查询公司信息
const getCompany = () => {
  contractCompany('CONTRACT_COMPANY_INFORMATION').then((res: any) => {
    const { address, companyAccountNumber, contactPhone, contactUser } = res.data;
    contractForm.value.companyAddress = address;
    contractForm.value.companyAccountNumber = companyAccountNumber;
    contractForm.value.companyContactPhone = contactPhone;
    contractForm.value.companyName = contactUser;
  });
};

// 获取类型中文名称
const getEnumsLabel = (val: any) => {
  let row = typeList.value.find((i: any) => i.value == val);
  return row ? row.label : "";
};

// 创建合同
const handleCreate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      if (contractForm.value.orderItems.length == 0) {
        ElMessage.warning("请添加合同订单");
        return;
      }
      let data = Object.assign({}, contractForm.value);
      data.orderItemIds = data.orderItems.map((i: any) => i.orderItemId);
      delete data.orderItems;
      contractAdd(data).then(() => {
        ElMessage.success("创建成功");
        router.go(-1);
      });
    }
  });
};

// 打开订单弹窗
const handleOrder = () => {
  getOrderList();
  orderShow.value = true;
};

// 获取订单列表
const getOrderList = () => {
  itemList(queryParams.value).then((res: any) => {
    orderList.value = res.rows;
    orderTotal.value = res.total;
  });
};

// 删除订单
const handleDelete = (row: any, index: number) => {
  contractForm.value.orderItems.splice(index, 1);
  amount.value = 0;
};

// 添加合同订单
const handleAdd = (row: any) => {
  amount.value = row.updatePrice;
  contractForm.value.orderItems.push(row);
  orderShow.value = false;
};
</script>
<style lang="less" scoped>
.title {
  .con-title {
    width: 100%;
    height: 50px;
    line-height: 50px;
    display: flex;
    align-items: center;
    span:nth-child(1) {
      display: flex;
      align-items: center;
      img {
        width: 14px;
        height: 14px;
      }
    }
    span:nth-child(2) {
      display: flex;
      align-items: center;
      margin-left: 10px;
      font-size: 16px;
    }
  }
}
.query {
  width: 100%;
  height: 50px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.tips {
  width: 100%;
  height: 54px;
  background: rgba(255, 110, 64, 0.1);
  padding-left: 50px;
  line-height: 54px;
}
.page-footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
.empty {
  display: flex;
  justify-content: center;
  align-items: center;
}
.listTitle2 {
  width: 100%;
  margin-bottom: 130px;
  height: 78px;
  border: 1px solid #f2f2f2;
  border-top: none;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #909090;
}
</style>
<style>
.title-style {
  height: 60px;
  background-color: #f6faff !important;
}
</style>
